//
//  LTLObject.m
//  WeiBo
//
//  Created by Apple_Lzzy46 on 16/9/27.
//  Copyright © 2016年 LTL. All rights reserved.
//

#import "LTLNetworkRequest.h"
#import "LTLhomeModel.h"
#import "LTLframeModel.h"

@interface  LTLNetworkRequest ()
@end
static FMDatabase *_db;
@implementation LTLNetworkRequest

//初始化
+ (void)initialize
{
    
    // 获取数据库文件的地址
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *sqlitePath = [docPath stringByAppendingPathComponent:@"status.sqlite"];
    // 创建数据库对象
    _db =  [FMDatabase databaseWithPath:sqlitePath];
    // 打开数据库
    if ([_db open]) {
        
        // 4.创建创建表, 添加字段
        NSString *sql =  @"CREATE TABLE IF NOT EXISTS t_status(id INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT, dict BLOB, idstr INTEGER, access_token TEXT)";
        if([_db executeUpdate:sql])
        {
            NSLog(@"创建表成功");
        }else
        {
            NSLog(@"创建表失败");
        }
    }
    
}
#pragma mark -  保存微博数据(存储到数据库)
+ (BOOL)saveStatusWithDict:(NSDictionary *)dict
{
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:NULL];
    NSString *idstr = dict[@"idstr"];
    NSString *access_token = [[LTLModel read] access_token];
    // ?号两边不能有单引号 哪怕是字符串
    BOOL success = [_db executeUpdate: @"INSERT INTO t_status(dict, idstr, access_token) VALUES(?, ?, ?);", data, idstr, access_token];
    return success;
}
#pragma mark -  读取微博数据(从数据库)
+ (NSArray <LTLframeModel*> *)statusesWithParametersSince_id:(  double ) since_id  max_id:( double )max_id
{
    NSMutableArray *models = [NSMutableArray array];
    FMResultSet *set = nil;
    NSString *access_token = [[LTLModel read] access_token];
    if (since_id != 0)
    {
        // 查询大于since_id的微博
        set = [_db executeQuery:@"SELECT * FROM t_status WHERE idstr > ? and access_token = ? ORDER BY idstr DESC LIMIT 0, 20;", [NSString stringWithFormat:@"%f",since_id], access_token];
    }else if (max_id != 0)
    {
        // 查询小于或等于max_id的微博
        set = [_db executeQuery:@"SELECT * FROM t_status WHERE idstr < ? and access_token = ? ORDER BY idstr DESC LIMIT 0, 20;", [NSString stringWithFormat:@"%f",max_id], access_token];
    }else
    {
        // 查询前20条微博
        set = [_db executeQuery:@"SELECT * FROM t_status WHERE access_token = ? ORDER BY idstr DESC LIMIT 0, 20;", access_token];
    }
    
    // 遍历所有查询到的结果, 将查询的结果转换为模型之后放入数组中返回
    while ([set next]) {
        // 1.取出存储的微博字典
        NSData *data = [set dataForColumn:@"dict"];
        // 2.将二进制转换为字典
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        // 3.将字典转换为模型
        LTLhomeModel  *status = [LTLhomeModel mj_objectWithKeyValues:dict];
        
        //模型再转模型
        LTLframeModel *frameMode = [[LTLframeModel alloc]init];
        
        frameMode.model = status;
        // 4.将模型添加到数组中
        [models addObject:frameMode];
    }

    return [models copy];
}
#pragma mark -
/**
 获取微博数据
 
 @param since_id 微博最大ID
 @param max_id   微博最小ID
 @param arrya    微博数据数组
 */
+ (void)statusWithParametersSince_id:(  double ) since_id  max_id:( double )max_id  arrya : ( arrya ) dadtArrya
{
    // 判断本地数据库是否有缓存数据
    NSArray *models = [self statusesWithParametersSince_id:since_id max_id:max_id];
    if (models.count > 0) {
        // 返回本地数据库缓存的数据
        if (dadtArrya) {
            dadtArrya(models);
        }
    }
    else
    {
        // 本地数据库没有缓存, 需要发送请求到服务器获取
        
        [self statuses_friends_timelineSince_id:since_id max_id:max_id arrya:^(NSArray<NSDictionary *> * _Nullable array) {
            
            [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ///缓存数据
                BOOL success =[self saveStatusWithDict:obj];
                if (success) {
                    NSLog(@"缓存微博数据成功");
                }else
                {
                    NSLog(@"缓存微博数据失败");
                }
                
            }];
            
            if (dadtArrya) {
                NSMutableArray *lingshi = [NSMutableArray array];
                //数据转模型
                NSArray <LTLhomeModel *> *model = [LTLhomeModel mj_objectArrayWithKeyValuesArray:array];
                //二次转换
                [model enumerateObjectsUsingBlock:^(LTLhomeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                    LTLframeModel *frameMode = [[LTLframeModel alloc]init];
                    
                    frameMode.model = obj;
                    
                    [lingshi addObject:frameMode];
                    
                }];
                dadtArrya(lingshi);
            }
            
        }];
        
    }
    
}

#pragma mark - 获取授权过的Access Token
/**
 *  获取授权过的Access Token
 *
 *  @param code 调用authorize获得的code值。
 */
+ (void) access_token : (NSString * _Nullable )code success: (LTL _Nullable) LTL
{
    
    NSString *str = @"https://api.weibo.com/oauth2/access_token";
    
    //字典
    NSDictionary *dict = @{ @"client_id" : client_id ,@"client_secret" : client_secret , @"grant_type" : @"authorization_code" , @"code" : code , @"redirect_uri" : redirect_uri };
    /**
     *  创建网络管理者
     */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //解析text/plain
    manager.responseSerializer.acceptableContentTypes  =  [NSSet setWithObject:@"text/plain"];
    //post请求
    [manager POST:str parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        LTLModel *model = [LTLModel LTLModelInitDict:responseObject];
        //获取当前用户信息
        [self users_show:model success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            
            NSDictionary *responseict = (NSDictionary *)responseObject;
            
            model.name = responseict[@"name"];
            
            model.avatar_hd =responseict[@"avatar_hd"];
            
            [model file];
            
            if (LTL) {
                
                LTL(task , responseObject);
            }

        }];
        
        NSLog(@"%@",model.name);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"access_token:%@", error);
        
    }];
}
#pragma mark - 获取用户信息
/**
 *  获取用户信息
 *
 *  @param model 授权过的Access Token
 */
+ (void) users_show:(LTLModel * _Nullable) model success: (LTL _Nullable) LTL 
{
    
    NSString *url = @"https://api.weibo.com/2/users/show.json";
    
    //参数字典
    NSDictionary *dict = @{ @"access_token" : model.access_token ,@"uid" : model.uid };
    /**
     *  创建网络管理者
     */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // NSLog(@"%@", responseObject);
        
        if (LTL) {
            
            LTL(task , responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"users_show:%@", error);
    }];
   // NSLog(@"%@",user.name);
}
 #pragma mark - 获取微博数据
 /**
  获取微博数据

  @param since_id 微博最大ID
  @param max_id   微博最小ID
  @param arrya    微博数据数组
  */
+ (void)statuses_friends_timelineSince_id:(  double ) since_id  max_id:( double )max_id  arrya :(nullable void(^)(NSArray <NSDictionary *>* _Nullable array ))arrya;
{

        LTLModel *shuJu = [LTLModel read];
        
        NSString *url = @"https://api.weibo.com/2/statuses/home_timeline.json";
        
        //参数字典
    NSDictionary *dict = @{ @"access_token" : shuJu.access_token , @"since_id" :  @(since_id)  ,  @"max_id" : @(max_id)  };
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
        
        [manager GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
//            NSLog(@"%@",responseObject);
            
            NSArray *array1 = responseObject[@"statuses"];
            
            if (arrya) {
                
                arrya(array1);
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"statuses_friends_timeline:%@", error);
        }];
    
}
#pragma mark - 获取未读数据
+ (void) unread_countSuccess: ( LTL  _Nonnull )LTL
{
    LTLModel *shuJu = [LTLModel read];
    
    NSString *url = @"https://rm.api.weibo.com/2/remind/unread_count.json";
    
    //参数字典
    NSDictionary *dict = @{ @"access_token" : shuJu.access_token , @"uid" : shuJu.uid};
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // manager = [AFHTTPRequestSerializer ]
    
    [manager GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        if (LTL) {
            
            LTL(task , responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"statuses_friends_timeline:%@", error);
    }];
}
/**
 发送微博
 
 @param text 要发送的文字
 @param image 要发送的图片
 @param LTL 发送成功的回调
 error 失败的回调
 */
+(void)faSong:(NSString *_Nonnull)text iamge:(UIImage *_Nonnull)image LTL :(nullable void(^)() )LTL error:(nullable void(^)() )Error
{
    //判断要要发送的微博是否有图片而调用不同的 URL
    NSString *url = image ?  @"https://upload.api.weibo.com/2/statuses/upload.json": @"https://api.weibo.com/2/statuses/update.json" ;
    
    LTLModel *shuJu = [LTLModel read];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    params[@"access_token"]=shuJu.access_token;
    
    params[@"status"]=text;
    ///管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    ///判断是否有图片而调用不同请求方法
    if (image) {
        ///将图片转为NSData
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        //计算大小因为微博不允许上传大于5M的照片
        NSInteger daxiao = data.length/(1000*1000);
        
        if (daxiao > 5 ) {
            [SVProgressHUD  showErrorWithStatus:@"图片大小不能大于5M!!"];
            return;
        }
        
        [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //上传图片
            [formData appendPartWithFileData:data name:@"pic" fileName:@"LTL.jpg" mimeType:@"iamge/jpeg"];
        
         } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             //提示
            [SVProgressHUD showSuccessWithStatus:@"发送成功"];
             if (LTL) {
                 //成功回调
                 LTL();
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             //提示
             [SVProgressHUD  showErrorWithStatus:@"发送失败"];
             NSLog(@"%@",error);
             if (Error) {
                 
                 Error();
             }
         }];
    } else {
        
        [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [SVProgressHUD showSuccessWithStatus:@"发送成功"];
            if (LTL) {
                //成功回调
                LTL();
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [SVProgressHUD  showErrorWithStatus:@"发送失败"];
            NSLog(@"%@",error);
            if (Error) {
                
                Error();
            }
        }];
    }
    
    
}



@end
